import { baseURL } from '@/api/base';
import axios from 'axios';
import {
  login as userLogin,
  LoginData,
} from '@/api/user';
import { useStorage } from '@vueuse/core';
import { getToken,setToken } from '@/utils/auth';



export interface HttpResponse<T = unknown> {
  status: number;
  msg: string;
  code: number;
  data: T;
}

const axiosInstance = axios.create({
    baseURL: baseURL,
    headers:{
        Authorization: getToken() || ''
    },
    timeout: 12000
});

axiosInstance.interceptors.request.use((config:any)=>{
    const token = localStorage.getItem("token")
    if(token){
      config.headers.Authorization = getToken() || ''
    }
    // const role = localStorage.getItem("role");
    let defaultParams = {};
    // if(role == 'street'){
    //   defaultParams = { 'street': localStorage.getItem("street")};
    // }else if(role == 'community'){
    //   defaultParams = { 'community': localStorage.getItem("community")};
    // }
    config.data  = { ...defaultParams, ...config.data  };
    // 判断角色 添加 
    return config
  },(error:any)=>{
    return Promise.reject(error)
  }
)

axiosInstance.interceptors.response.use(async (response:any) =>{
  return response;
},async (error)=>{
  if (error && error.response) {
    if (error.response.status === 401) {
      const loginConfig = useStorage('login-config', {
        rememberPassword: true,
        username: '', //默认值
        password: '', //默认值
      });
      const loginForm:LoginData = ({
        username: loginConfig.value.username,
        password: loginConfig.value.password,
      });
      console.log(loginForm);
      const loginRes = await userLogin(loginForm);
      console.log(loginRes);
      setToken(loginRes.data.result.access_token);
      return;
    }
  }
})


// axiosInstance.interceptors.response.use(async (response:any) =>{
//     console.log(response);  
//     if (response.status === 401) {
//         const loginConfig = useStorage('login-config', {
//           rememberPassword: true,
//           username: '', //默认值
//           password: '', //默认值
//         });
//         const loginForm:LoginData = ({
//           username: loginConfig.value.username,
//           password: loginConfig.value.password,
//         });
//         const loginRes = await userLogin(loginForm);
//         if(loginRes.data.code == 200){
//             setToken(loginRes.data.result.access_token);
//             // 重新请求
//             response.config.headers.Authorization = getToken() || ''
//             const resp = await axiosInstance.request(response.config);
//             return resp;
//         }
//     }
//     return response;
// }
// ,error=>{
//   if (error && error.response) {
//   }
// }
// )
export default axiosInstance;